# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


class Solution:
    def buildTree(self, preorder, inorder) -> TreeNode:
        if len(preorder) == 0 or len(inorder) == 0:
            return None
        root = TreeNode(preorder[0])
        root_index = inorder.index(preorder[0])
        left = self.buildTree(preorder[1:root_index+1], inorder[:root_index])
        right = self.buildTree(preorder[1 + root_index:], inorder[root_index + 1:])
        root.left = left
        root.right = right
        return root


if __name__ == '__main__':
    so = Solution()
    preorder = [3,9,20,15,7]
    inorder = [9,3,15,20,7]
    r = so.buildTree(preorder, inorder)
    print(r)
